package server

import (
	"226zy/common/moels/mysql"
	"226zy/common/moels/redis"
	"226zy/common/proto/user"
	"context"
	"fmt"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	u := mysql.User{}
	getUser, err := u.GetUser(in.Name)
	if err != nil {
		return &user.LoginResp{Greet: "查询失败"}, nil
	}
	if getUser.Phone == "" {
		m := mysql.User{
			Model:    gorm.Model{ID: getUser.ID},
			Phone:    in.Name,
			Password: in.Password,
		}
		err := u.Create(m)
		if err != nil {
			return &user.LoginResp{Greet: "注册失败"}, nil
		}
	}
	if getUser.Password != in.Password {
		return &user.LoginResp{Greet: "密码错误"}, nil
	}
	return &user.LoginResp{Greet: strconv.Itoa(int(getUser.ID))}, nil
}

func List(in *user.ListReq) (*user.ListResp, error) {
	u := mysql.User{}
	listUser, err := u.ListUser()
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}

	var lists []*user.List
	for _, u2 := range listUser {
		lists = append(lists, &user.List{
			Phone:    u2.Phone,
			Password: u2.Password,
		})
	}
	key := "list" + "1"
	redis.Rdb.HSet(context.Background(), key, lists, time.Minute*24)

	return &user.ListResp{List: lists}, nil
}
